package org.devf.fork.imsimulator.service;

import cn.hutool.json.JSONUtil;
import javafx.scene.Node;
import javafx.scene.input.Dragboard;
import javafx.scene.input.TransferMode;
import org.devf.fork.imsimulator.help.ImgUtil;
import org.devf.fork.imsimulator.help.MyLog;
import org.devf.fork.imsimulator.help.ThreadUtil;
import org.devf.fork.imsimulator.model.DeviceUserModel;
import org.devf.fork.imsimulator.service.chat.ChatMgrFactory;
import org.devf.fork.imsimulator.service.vo.UserExtendModel;
import org.devf.fork.imsimulator.socket.TcpClientFactory;
import org.devf.fork.imsimulator.socket.dto.BasePackets;
import org.devf.fork.imsimulator.socket.dto.BizType;
import org.devf.fork.imsimulator.socket.dto.MsgStatus;
import org.devf.fork.imsimulator.view.extend.DragFileListener;

import java.io.File;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * ChatService related
 *
 * @author wanghuafu
 * @since 0.1 2023/9/13
 */
public class ChatService {

    ThreadPoolExecutor executor = ThreadUtil.newExecutorByBlockingCoefficient(0.3f);
    FriendService friendService = ServiceFactory.getSingleFriendService();

    /**
     * 保存收到的消息
     * @param packets 数据报
     */
    public void saveMessageOfReceipt(BasePackets packets){
        String from = packets.getFromDeviceId();
        DeviceUserModel devFrom = new DeviceUserModel(from);

        //查询用户信息
        UserExtendModel userExtendModel = friendService.getUserInfo(devFrom.getUserId());
        if (null == userExtendModel){
            MyLog.info("收到对方消息，但是无法保存，对方用户信息查询不到");
            return;
        }

        //单聊? 群聊就要用关系ID或者其他了
        ChatMgrFactory.getMemoryChat().putChatMessage(userExtendModel.getId(),userExtendModel,packets);
    }



    /**
     * 发送消息
     * @param packets 消息
     */
    public void sendChatMsg(UserExtendModel dest , BasePackets packets){
        ChatMgrFactory.getMemoryChat().putChatMessage(dest.getId(),dest,packets);
        TcpClientFactory.getDefault().getChannel()
                .write(JSONUtil.toJsonStr(packets));
    }



    public void updateState(BasePackets packets) {
        if (packets.getBizType().equals(BizType.SINGLE_CHAT.name())){
            ChatMgrFactory.getMemoryChat().updateMessageState(
                    Long.valueOf(packets.getDestDeviceId()),//单聊的情况下
                    packets.getPackageId(),
                    MsgStatus.getByCode(packets.getMsgStatus()));
        }
    }

    public void syncSendChatMsg(UserExtendModel focusFriendUser, BasePackets packets) {
        executor.execute(()-> sendChatMsg(focusFriendUser,packets));
    }

    public ThreadPoolExecutor getExecutor() {
        return executor;
    }

    public void addEventOfDragFile(Node listView, DragFileListener consumer) {
        // 拖拽区域
        listView.setOnDragOver(event -> {
            if (event.getGestureSource() != listView
                    && event.getDragboard().hasFiles()) {
                event.acceptTransferModes(TransferMode.COPY_OR_MOVE);
            }
            event.consume();
        });

        // 处理拖拽放下事件
        listView.setOnDragDropped(event -> {
            Dragboard db = event.getDragboard();
            boolean success = false;
            if (db.hasFiles()) {
                File file = db.getFiles().get(0);
                if (ImgUtil.isImg(file.getName())){
                    consumer.onDragImageOfSend(file);
                }else{
                    MyLog.info("只支持png/jpg");
                }
                success = true;
            }
            event.setDropCompleted(success);
            event.consume();
        });

    }
}
